package cn.initcap.concurrency.classloader;

import java.io.IOException;
import java.io.InputStream;

/**
 * 只有两个类由同一个类加载器加载的前提下，比较两个类的相等才由意义，只要加载他们的类加载器不同，那这两个
 * 类就必定不相等。
 * <p>
 * 类加载器与instanceof关键字演示
 *
 * @author initcap
 * @date Created in 2018/7/25 AM10:54.
 */
public class ClassLoaderTest {

    public static void main(String[] args) throws Exception {
        ClassLoader myLoader = new ClassLoader() {
            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException {
                try {
                    String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class";
                    InputStream is = getClass().getResourceAsStream(fileName);
                    if (is == null) {
                        return super.loadClass(name);
                    }
                    byte[] b = new byte[is.available()];
                    is.read(b);
                    return defineClass(name, b, 0, b.length);
                } catch (IOException e) {
                    throw new ClassNotFoundException(name);
                }
            }
        };
        Object obj = myLoader.loadClass("cn.initcap.classloader.ClassLoaderTest").newInstance();
        System.out.println(obj.getClass());
        //这里obj为自定义的类加载器加载的，而cn.initcap.classloader.concurrency.ClassLoaderTest为默认加载起加载，不同加载器加载相同的类结果为false.
        System.out.println(obj instanceof cn.initcap.concurrency.classloader.ClassLoaderTest);
    }

}
